package com.wude.guild.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.mc.developmentkit.utils.ToastUtil;
import com.mc.developmentkit.views.SimpleFooter;
import com.mc.developmentkit.views.SpringView;
import com.wude.bean.JifenDetailBean;
import com.wude.bean.JifenStoreBean;
import com.wude.guild.JifenStoreActivity;
import com.wude.guild.R;
import com.wude.guild.adapter.JifenStoreAdapter;
import com.wude.guild.servercore.mints.TitleBaseFragment;
import com.wude.http.HttpCom;
import com.wude.tools.RecycleViewDivider;
import com.wude.tools.SpacesItemDecoration;
import com.wude.tools.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 唐小妹 on 2017/12/13 0013.
 * <p>
 * 积分商城
 */

public class JifenStoreFragment extends TitleBaseFragment implements View.OnClickListener {
    private SpringView springview;
    private RecyclerView rv_goods;
    private JifenStoreAdapter adapter;
    private TextView tv_jifenRecord;
    private TextView tv_point;

    private JifenStoreActivity activity;

    private List<JifenStoreBean> dataList = new ArrayList<>();
    private int limit = 1;
    private boolean isMore = false;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_jifen_store, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        setHeaderTitle("积分商城");

        ImageView rightImageView = getTitleHeaderBar().getRightImageView();
        rightImageView.setImageResource(R.mipmap.jifen_rule);
        rightImageView.setOnClickListener(this);

        initView(view);
    }


    @Override
    public void onResume() {
        super.onResume();
        rv_goods.setFocusable(false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = (JifenStoreActivity) activity;
    }

    private void initView(View view) {
        rv_goods = view.findViewById(R.id.rv_goods);
        tv_jifenRecord = view.findViewById(R.id.tv_jifenRecord);
        springview = findView(view, R.id.springview);
        tv_point = findView(view, R.id.tv_point);
        rv_goods.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));

        springview.setType(SpringView.Type.FOLLOW);
        springview.setListener(onFreshListener);
//        springview.setHeader(new SimpleHeader(getActivity()));
        springview.setFooter(new SimpleFooter(getActivity()));

        //设置item之间的间隔
        SpacesItemDecoration decoration = new SpacesItemDecoration(30);
        rv_goods.addItemDecoration(decoration);
        //设置分割线
        rv_goods.addItemDecoration(new RecycleViewDivider(
                getContext(), LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.eee)));
        rv_goods.addItemDecoration(new RecycleViewDivider(
                getContext(), LinearLayoutManager.HORIZONTAL, 2, getResources().getColor(R.color.eee)));

        initAndReflsh(false);

        adapter = new JifenStoreAdapter(getActivity());
        rv_goods.setAdapter(adapter);


        tv_jifenRecord.setOnClickListener(this);
    }

    SpringView.OnFreshListener onFreshListener = new SpringView.OnFreshListener() {
        @Override
        public void onRefresh() {
            initAndReflsh(false);
            isMore = false;
        }

        @Override
        public void onLoadmore() {
            initAndReflsh(true);
            isMore = true;
        }
    };

    private void initAndReflsh(boolean isMore) {
        if (!isMore) {
            dataList.clear();
            limit = 1;
        } else
            limit = ++limit;
        //数据请求
        Map<String, String> map = new HashMap<>();
        map.put("token", Utils.getLoginUser().token);
        map.put("p", limit + "");
        HttpCom.POST(handler, HttpCom.getGetPointShopList(), map, false);
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            springview.onFinishFreshAndLoad();
            switch (msg.what) {
                case 1:
                    DNSData(msg.obj.toString());
                    break;
                case 2:
                    ToastUtil.showToast("网络错误");
                    springview.setVisibility(View.GONE);
                    break;
            }
        }
    };


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.right_image:
                activity.pushFragmentToBackStack(JifenRuleFragment.class, null);
                break;
            case R.id.tv_jifenRecord:
                activity.pushFragmentToBackStack(JifenDetailFragment.class, "jifenRecord");
                break;
        }
    }

    private void DNSData(String str) {
        Log.d("json", str);
        try {
            JSONObject jsonObject = new JSONObject(str);
            int status = jsonObject.getInt("status");
            if (status == 1) {
                JSONObject data = jsonObject.getJSONObject("data");
                tv_point.setText("可用积分：" + data.getString("point"));
                JSONArray detail = data.getJSONArray("data");
                if (detail != null) {
                    for (int i = 0; i < detail.length(); i++) {
                        JSONObject detailObj = detail.getJSONObject(i);
                        JifenStoreBean bean = new JifenStoreBean();
                        bean.id = detailObj.getInt("id");
                        bean.cover = detailObj.getString("cover");
                        bean.good_name = detailObj.getString("good_name");
                        bean.price = detailObj.getString("price");
                        bean.good_usage = detailObj.getString("good_usage");
                        dataList.add(bean);
                    }
                    adapter.setDataList(dataList);
                } else {
                    ToastUtil.showToast(isMore ? "已经到底了" : "没有数据哦");
                }
            } else {
                ToastUtil.showToast(jsonObject.getString("return_code"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
